﻿using AiBLSmartEdu.Module.Cust.API.DTOs;
using AutoMapper;
using Domain.Entities;
using FrameworkCore.DI;
using FrameworkCore.Migrations;
using FrameworkCore.Repositories;
using Microsoft.EntityFrameworkCore.Query;
using System.Linq.Expressions;
using FrameworkCore.Helpers;
using Microsoft.EntityFrameworkCore;
using FrameworkCore.Interfaces;
using FrameworkCore.Extensions;
using FrameworkCore.Models;

namespace AiBLSmartEdu.Module.Cust.API.Repositories;

#nullable disable

public class CustomerRepository : RepositoryBase<Customer>, IScopedDependency
{
    private readonly IAiBLSmartEduDataProvider _dataProvider;
    private readonly IMapper _mapper;
    private readonly ICurrentUserService  _currentUserService;
    public CustomerRepository(
        IAiBLSmartEduDataProvider dataProvider,
        IMapper mapper,
        ICurrentUserService currentUserService) : base(dataProvider, currentUserService)
    {
        _dataProvider = dataProvider;
        _mapper = mapper;
        _currentUserService = currentUserService;
    }

    /// <summary>
    /// 启用/停用
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public async Task<bool> IsEnabledAsync(long id)
    {
        Expression<Func<SetPropertyCalls<Customer>, SetPropertyCalls<Customer>>>
            setPropertyCalls = x => x.SetProperty(p => p.IsEnabled, p => !p.IsEnabled);

        Expression<Func<Customer, bool>> predicate = p => p.Id == id;

        return await _dataProvider.BulkUpdateEntitiesAsync(setPropertyCalls, predicate) > 0;
    }

    /// <summary>
    /// 分页查询
    /// </summary>
    /// <param name="filter">分页输入模型</param>
    /// <returns></returns>
    public async Task<PageResult<CustomerOutputModel>> PageAsync(CustomerPaginationFilter filter)
    {
        return (await GetOrderedQueryable(query =>
        {
            return query.WhereIf(!filter.Email.IsNullOrWhiteSpace(), x => x.Email.Contains(filter.Email))
                        .WhereIf(!filter.Username.IsNullOrWhiteSpace(), x => x.Username.Contains(filter.Username));


        }, filter).ProjectToPaginatedDataAsync<Customer, CustomerOutputModel>(
            filter.PageNumber,
            filter.PageSize,
            _mapper.ConfigurationProvider
        )).ToPageList();
    }

    /// <summary>
    /// 获取用户信息
    /// </summary>
    /// <returns></returns>
    public async Task<CustomerOutputModel> GetCustInfo()
    {        
        return _mapper.Map<CustomerOutputModel>(await GetByIdAsync(_currentUserService.CurrentUserId));
    }

    /// <summary>
    /// 创建用户
    /// </summary>
    /// <param name="input">输入模型</param>
    /// <returns></returns>
    public async Task CreateAsync(CustomerCreateInputModel input)
    {
        var userNameToExist = await Query(x => x.Username == input.Username).AnyAsync();
        ExceptionHelper.ThrowIfTrue(userNameToExist, $"用户名{input.Username}已存在");

        var model = _mapper.Map<Customer>(input);
        model.HashPassword(input.Password);
        await InsertAsync(model);
    }

    /// <summary>
    /// 修改用户
    /// </summary>
    /// <param name="input">输入模型</param>
    /// <returns></returns>
    public async Task UpdateEmailAsync(CustomerUpdateEmailInputModel input)
    {
        input.Id = input.Id ?? _currentUserService.CurrentUserId;
        var customer = await GetByIdAsync(input.Id);
        ExceptionHelper.ThrowIfNull(customer, "用户不存在");

        await UpdateAsync(x => x.SetProperty(p => p.Email, p => input.Email), w => w.Id == input.Id);
    }

    /// <summary>
    /// 修改用户头像
    /// </summary>
    /// <param name="input">输入模型</param>
    /// <returns></returns>
    public async Task UpdateAvatarAsync(UpdateAvatarInputModel input)
    {
        var customer = await GetByIdAsync(_currentUserService.CurrentUserId);
        ExceptionHelper.ThrowIfNull(customer, "用户不存在");

        _mapper.Map(input, customer);
        await UpdateAsync(customer);
    }

    /// <summary>
    /// 删除用户
    /// </summary>
    /// <param name="ids">唯一标识，多个使用英文状态下的逗号（,）隔开</param>
    /// <returns></returns>
    public async Task DeleteAsync(string ids)
    {
        ExceptionHelper.ThrowIfNull(ids, "删除的唯一标识不能为空");

        List<long> idsToDelste = ids
            .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)  // 分割字符串
            .Select(id =>
            {
                if (long.TryParse(id.Trim(), out long result))
                {
                    return result;
                }
                else
                {
                    ExceptionHelper.ThrowIfTrue(true, "无效的标识");
                    return 0;
                }
            }).ToList();

        await DeleteAsync(x => idsToDelste.Contains(x.Id));
    }
}
